﻿using System;
using System.Web;
using System.Net.Mail;
using System.Web.UI;
using SimplePMT.Data;
using SimplePMT.Control;
using System.Text;
using System.Collections.Generic;
using Castle.ActiveRecord;
using NHibernate.Expression;
using SimplePMT.Components;
using System.Threading;

namespace SimplePMT
{
    public partial class QuickTimeEntry : Components.BasePage
    {
        
        public string taskView = string.Empty;
        public string taskId = string.Empty;
        public int parentContainerId = 0;
        public string memberId = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(QuickTimeEntry), this.Page);
            ValidateSession();
            Control.QuickTimeEntryControl view = this.LoadControl("./Control/QuickTimeEntryControl.ascx") as Control.QuickTimeEntryControl;
            view.edit = true;
            view.taskid = Convert.ToInt32(Request.QueryString["id"]);
            view.taskContainerId = Convert.ToInt32(Request.QueryString["cid"]);
            parentContainerId = TaskContainer.Find(view.taskContainerId).ParentContainerID;
            taskId = view.taskid.ToString();
            taskView = view.ToString();
            memberId = Session["MemberID"].ToString();
        }

        [AjaxPro.AjaxMethod()]
        public bool AddTaskNote(int taskId, string note, int MemberID, string hours, string noteDate)
        {
            using (new SessionScope())
            {
                try
                {
                    TaskNote taskNote = new TaskNote();
                    taskNote.IsSVNSource = false;
                    taskNote.Member = Member.Find(MemberID);
                    taskNote.Notes = note;
                    taskNote.DateTime = Convert.ToDateTime(noteDate);
                    taskNote.Task = Task.Find(taskId);
                    taskNote.Hours = Convert.ToDecimal(hours);
                    taskNote.Save();
                    TaskContainerItem[] items = TaskContainerItem.FindAllByProperty("TaskID", taskId);
                    if (items.Length > 0)
                    {
                        Control.TaskNotification view = this.LoadControl("./Control/TaskNotification.ascx") as Control.TaskNotification;

                        Task t = Task.Find(taskId);
                        view.taskid = t.ID;
                        view.taskContainerId = items[0].TaskContainer.ID;
                        view.edit = false;

                        if (t.AssignedMemberID > 0)
                        {
                            try
                            {
                                AppConfiguration config = AppConfiguration.FindAllByProperty("ConfigActive", true)[0];
                                MailMessage msg = new MailMessage(config.SMTPFromAddress, Member.Find(t.AssignedMemberID).EmailAddress, "AWISH Note Update: " + t.Title, "<span style=\"font-family: Tahoma;font-size: 13px;\">Notes have been updated in: " + Common.GetRecursiveTaskTreePath(TaskContainer.Find(items[0].TaskContainer.ID)) + "\r\n<p/>\r\n" + config.SiteUrl + "</span>\r\n<p>\r\n" + view.ToString());
                                SmtpClient client = new SmtpClient(config.SMTPServer, config.SMTPPort);
                                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                                client.UseDefaultCredentials = false;
                                client.Credentials = new System.Net.NetworkCredential(config.SMTPUser, config.SMTPPass);
                                msg.IsBodyHtml = true;
                                client.Send(msg);
                            } catch { // Squishing exceptions, just to bug the efffff out of Mr. Carter.... enjoy.

                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    throw new Exception(err.StackTrace);
                }
            }
            return true;
        }

        [AjaxPro.AjaxMethod()]
        public bool UpdateTaskNote(int taskId, int taskNoteId, string note, int MemberID, string hours, string noteDate)
        {
            using (new SessionScope())
            {
                try
                {
                    TaskNote taskNote = TaskNote.Find(taskNoteId) ?? new TaskNote();
                    taskNote.IsSVNSource = false;
                    taskNote.Member = Member.Find(MemberID);
                    taskNote.Notes = note;
                    taskNote.DateTime = Convert.ToDateTime(noteDate);
                    taskNote.Task = Task.Find(taskId);
                    taskNote.Hours = Convert.ToDecimal(hours);
                    taskNote.Save();
                    
                }
                catch (Exception err)
                {
                    throw new Exception(err.StackTrace);
                }
            }
            return true;
        }

        [AjaxPro.AjaxMethod()]
        public bool DeleteTask(int taskId)
        {
            TaskContainerItem[] itms = TaskContainerItem.FindAllByProperty("TaskID", taskId);
            foreach (TaskContainerItem itm in itms)
            {
                itm.Delete();
            }
            Task t = Task.Find(taskId);
            t.Delete();
            return true;
        }

        [AjaxPro.AjaxMethod()]
        public object[] SaveTask(int ReleaseID, int taskStatus, string dueDate, string taskContainerId, int taskId, int taskTypeId, string taskTitle, string taskDescription, int createMemberId, int assignedMemberId, string hoursEstimated, string hoursActual, int complexityEstimated, int complexityActual, bool isComplete, string note, int priorityId, string noteDate)
        {
            string messages = "";
            Task task = Task.Find(taskId) ?? new Task();
            int originalAssigned = task.AssignedMemberID;
            TaskContainer tc = TaskContainer.Find(Convert.ToInt32(taskContainerId));
            
            task.IsAccepted = false;
            task.IsOnHold = false;
            task.IsResolved = false;
            task.IsAccepted = false;
            task.IsWorking = false;

            if (taskStatus.Equals(1)) {
                task.IsAccepted = true;
            } else if (taskStatus.Equals(2)) {
                task.IsOnHold = true;
            } else if (taskStatus.Equals(3)) {
                task.IsWorking = true;
            } else if (taskStatus.Equals(4)) {
                task.IsResolved = true;
            }
            task.TaskType = TaskType.Find(taskTypeId);
            task.Title = taskTitle.Replace("&quot;", "\"");
            task.Priority = Priority.Find(priorityId);
            task.Description = taskDescription;
            task.NotificationID = 1;
            task.AssignedMemberID = assignedMemberId;
            Member assigned = Member.Find(assignedMemberId) ?? new Member();

            task.DueDate = Convert.ToDateTime(dueDate);

            if (ReleaseID > 0)
            {
                Release r = Release.Find(ReleaseID);
                if (task.DueDate < r.ReleaseDateCutoff)
                {
                    task.ReleaseID = ReleaseID;
                }
                else
                {
                    messages = "Release Selected Not Allowed\n\nTask due date is greater than the cut-off date of the specified release.";
                    task.ReleaseID = 0;
                }
            }
            if (!task.AssignedMemberID.Equals(0))
            {
                task.AssignedDateTime = DateTime.Now;
            }
            if (task.ID == 0)
            {

                task.CreateDateTime = DateTime.Now;
                task.CreateMemberID = createMemberId;
                task.HoursEstimated = Convert.ToDecimal(hoursEstimated);
                task.ClosedDateTime = Convert.ToDateTime("1/1/1900 12:00:00 AM");
                task.ComplexityEstimatedID = complexityEstimated;
            }
            else
            {
                task.HoursActual = Convert.ToDecimal(hoursActual);
                task.ComplexityActualID = complexityActual;
                if (note.Trim() != "")
                {
                    TaskNote taskNote = new TaskNote();
                    taskNote.Member = Member.Find(createMemberId);
                    taskNote.DateTime = DateTime.Now;
                    taskNote.IsSVNSource = false;
                    taskNote.Notes = note;
                    taskNote.Hours = Convert.ToDecimal(hoursActual);
                    taskNote.DateTime = Convert.ToDateTime(noteDate);
                    taskNote.Task = task;
                    taskNote.Save();
                }
                if (isComplete)
                {
                    task.ClosedDateTime = DateTime.Now;
                }
            }
            task.Save();
            
            TaskContainerItem[] items = TaskContainerItem.FindAll(Expression.Eq("TaskContainer", tc), Expression.Eq("TaskID", task.ID));
            if (items.Length.Equals(0))
            {
                TaskContainerItem item = new TaskContainerItem();
                item.TaskContainer = tc;
                item.TaskID = task.ID;
                item.Save();
            }

            AppConfiguration config = AppConfiguration.FindAllByProperty("ConfigActive", true)[0];
            if (!originalAssigned.Equals(assignedMemberId) && !config.SMTPPort.Equals(0))
            {
                Control.TaskNotification view = this.LoadControl("./Control/TaskNotification.ascx") as Control.TaskNotification;
                view.edit = true;
                view.taskid = task.ID;
                view.taskContainerId = Convert.ToInt32(taskContainerId);
                if (assignedMemberId > 0)
                {
                    try
                    {
                        MailMessage msg = new MailMessage(config.SMTPFromAddress, assigned.EmailAddress, "AWISH: " + task.Title, "<span style=\"font-family: Tahoma;font-size: 13px;\">A new task has been assigned to you in: " + Common.GetRecursiveTaskTreePath(TaskContainer.Find(Convert.ToInt32(taskContainerId))) + "\r\n<p/>\r\n" + config.SiteUrl + "</span>\r\n<p>\r\n" + view.ToString());
                        SmtpClient client = new SmtpClient(config.SMTPServer, config.SMTPPort);
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        client.UseDefaultCredentials = false;
                        client.Credentials = new System.Net.NetworkCredential(config.SMTPUser, config.SMTPPass);
                        msg.IsBodyHtml = true;
                        client.Send(msg);
                    }
                    catch
                    { // Squishing exceptions, just to bug the efffff out of Mr. Carter.... enjoy.

                    }
                }
            }
            if (!task.ClosedDateTime.Equals(Convert.ToDateTime("1/1/1900")) && !config.SMTPPort.Equals(0))
            {
                Member assignor = Member.Find(task.CreateMemberID);

                Control.TaskNotification view = this.LoadControl("./Control/TaskNotification.ascx") as Control.TaskNotification;
                view.edit = true;
                view.taskid = task.ID;
                view.taskContainerId = Convert.ToInt32(taskContainerId);
                if (assignor.ID > 0)
                {
                    try
                    {
                        MailMessage msg = new MailMessage(config.SMTPFromAddress, assignor.EmailAddress, "AWISH: " + task.Title + " completed", "<span style=\"font-family: Tahoma;font-size: 13px;\">A task you have assigned is now complete: " + Common.GetRecursiveTaskTreePath(TaskContainer.Find(Convert.ToInt32(taskContainerId))) + "\r\n<p/>\r\n" + config.SiteUrl + "</span>\r\n<p/>\r\n" + view.ToString());
                        SmtpClient client = new SmtpClient(config.SMTPServer, config.SMTPPort);
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        client.UseDefaultCredentials = false;
                        client.Credentials = new System.Net.NetworkCredential(config.SMTPUser, config.SMTPPass);
                        msg.IsBodyHtml = true;
                        client.Send(msg);
                    }
                    catch
                    { // Squishing exceptions, just to bug the efffff out of Mr. Carter.... enjoy.

                    }
                }
            }


            return new object[] { true, task.ID, messages};

        }

        [AjaxPro.AjaxMethod()]
        public static string GetTaskNotes(int taskId)
        {
            return GetTaskNotes(taskId, false);
        }

        [AjaxPro.AjaxMethod()]
        public static string[] GetEditTaskNote(int taskId)
        {
            TaskNote note = TaskNote.Find(taskId);
            return new string[] { note.Notes, note.Hours.ToString(), note.DateTime.ToShortDateString() };
        }

        public static string GetTaskNotes(int taskId, bool showAll)
        {
            bool ReadOnly = false;
            if (HttpContext.Current.Session["MemberID"] != null)
            {
                Member member = Member.Find(Convert.ToInt32(HttpContext.Current.Session["MemberID"]));
                ReadOnly = member.ReadOnly;
            }
            IList<TaskNote> notes = TaskNote.FindAll(new Order("DateTime", false), Expression.Eq("Task.ID", taskId));
            StringBuilder output = new StringBuilder();
            output.Append("<table cellpadding=3 cellspacing=0 width=100% style=\"font-family: Tahoma;font-size: 12px;\">\n");
            using (new SessionScope())
            {
                foreach (TaskNote note in notes)
                {
                    output.Append("<tr bgcolor=\"#C7DCF5\"");
                    if (!showAll) {
                        output.Append("OnClick=\"showNote('note" + note.ID + "');\" OnMouseOver=\"this.style.backgroundColor='#9BC0ED';this.style.cursor='pointer';\" OnMouseOut=\"this.style.backgroundColor='#C7DCF5'\"");
                    }
                    output.Append(">\n");
                    output.Append(" <td>" + note.DateTime.ToShortDateString() + "</td>\n");
                    output.Append(" <td> by " + note.Member.FirstName + " " + note.Member.LastName + " ("+ note.Hours +" hours)</td>\n");
                    output.Append("</tr>\n");
                    output.Append("<tr id=\"note" + note.ID + "\"");
                    if (!showAll) {
                        output.Append("style=\"display:none\"");
                    }
                    output.Append(">\n");
                    output.Append(" <td colspan=2>" + Common.ConvertToHTML(note.Notes));
                    if (!showAll && !ReadOnly)
                    {
                        output.Append("<p><button type=\"button\" OnClick=\"editNote(" + note.ID + ");\">Edit</button>\n");
                    }
                    output.Append("</td></tr>\n");
                    
                    output.Append("<tr><td colspan=2 height=1></td></tr>");
                }
            }
            if (notes.Count == 0)
            {
                output.Append("<tr>\n");
                output.Append(" <td colspan=2>No notes curently exist.</td>\n");
                output.Append("</tr>\n");
            }
            output.Append("</table>");
            return output.ToString();
        }
    }
}
